const Sequelize = require("sequelize");
const config = configure.get('db');
const Op = Sequelize.Op;

const operatorsAliases = {
    $eq: Op.eq,
    $ne: Op.ne,
    $gte: Op.gte,
    $gt: Op.gt,
    $lte: Op.lte,
    $lt: Op.lt,
    $not: Op.not,
    $in: Op.in,
    $notIn: Op.notIn,
    $is: Op.is,
    $like: Op.like,
    $notLike: Op.notLike,
    $iLike: Op.iLike,
    $notILike: Op.notILike,
    $regexp: Op.regexp,
    $notRegexp: Op.notRegexp,
    $iRegexp: Op.iRegexp,
    $notIRegexp: Op.notIRegexp,
    $between: Op.between,
    $notBetween: Op.notBetween,
    $overlap: Op.overlap,
    $contains: Op.contains,
    $contained: Op.contained,
    $adjacent: Op.adjacent,
    $strictLeft: Op.strictLeft,
    $strictRight: Op.strictRight,
    $noExtendRight: Op.noExtendRight,
    $noExtendLeft: Op.noExtendLeft,
    $and: Op.and,
    $or: Op.or,
    $any: Op.any,
    $all: Op.all,
    $values: Op.values,
    $col: Op.col
};

let connections = [];

Object.keys(config).forEach(function (name) {
    let cname = config[name];
    cname.operatorsAliases = operatorsAliases;

    connections.push({
        name: name,
        sequelize: new Sequelize(config[name].database, config[name].username, config[name].password, cname),
        Sequelize: Sequelize
    })
});

let db = function (name) {
    name = name || 'default';
    return db[name];
};

connections.forEach(function (conn) {
    let conn_name = conn.name;

    let models = {};
    let model_dir = path.join(process.cwd(), 'resources', 'models', conn_name);
    fs.existsSync(model_dir) || fs.mkdirSync(model_dir);

    fs.readdirSync(model_dir)
        .filter(function (file) {
            return (path.extname(file) === '.js');
        })
        .forEach(function (file) {
            let model = conn.sequelize.import(path.join(process.cwd(), 'resources', 'models', conn_name, file));
            models[model.name] = model;
        });

    db[conn_name] = models;
    db[conn_name].sequelize = conn.sequelize;
    db[conn_name].Sequelize = conn.Sequelize;
});

module.exports = db;